<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
  <div class="my-group-data">

    <avue-crud
        v-model:search="form"
        :option="option"
        @search-change="searchChange"
    >
    </avue-crud>


    <div style="margin: 20px;">
      <div v-for="tList in tableDataList">
        <h3>{{tList.title}}</h3>
        <el-table :data="tList.data" style="width: 100%">
          <el-table-column
              width="120"
              v-for="column in tList.clomns"
              :key="column.v"
              :prop="column.v"
              :label="column.k">
          </el-table-column>
        </el-table>

      </div>
    </div>


  </div>


</template>
<script>
  import {pageCore,listCore,delCore,getCore,saveCore,importCore,exportCore,downloadCore} from "@/framework-core/api/core/api";
  import {queryByApp} from "@/framework-admin/api/code/formquery";
  import request from '@/framework-core/axios';
  import website from '@/framework-core/config/website';
  import { convertHtmlByParam,convertVantMobile,removeEmptyFields,loadEChartsScript} from '@/framework-core/utils/util'
  // import * as echarts from 'echarts'
  import {getFormModel} from "@/framework-admin/api/code/formmodel";
  import Table from "@/framework-core/views/util/table.vue";

  export default {
    name: "formq",
    components: {Table},
      data() {
          return {

            rangList: [],
            appCode: "",
            pageConfig: {"url": "/form/tableData"},
            loading: false,
            option: {},
            form: {},
            tableData: [],
            sysParamForm: {},
            groupTitleMap: {},
            mysearch: {},
            queryFormData: {},
            groupDics: [],
            groupDicMap: {},
            tableDataList: [],
            tableDicMap:{},
          };
      },
    computed: {
      ...mapState({
        permissions: (state) =>state.user.permission,
      }),
    },
    created() {
        this.init();
        this.getFormJson();

    },
    methods: {
        init() {

            Object.keys(this.$route.query).forEach((key) => {
                this.form[key] = this.$route.query[key];
            });

      },
      searchChange(form, done) {
        this.getPage();
        done();
      },

        // resizeChart() {
        //     if (this.$refs.echartsId) {
        //         this.$refs.echartsId.resize()
        //        // console.log('1111')
        //     }
        // },
        getFormJson() {
          this.option = {
            "border": true,
            "index": true,
            "indexLabel": "#",
            "stripe": true,
            "menuAlign": "center",
            "align": "center",
            searchLabelWidth: 150,
            editBtn: false,
            saveBtn: false,
            addBtn: false,
            delBtn: false,
            "searchMenuSpan": 6,
            grid: window.isMobile,
            gridSpan: 24,
            "column": []
          };
            this.appCode = this.$route.query.app;
          this.groupDicMap = {};
          this.groupDics = [];
            queryByApp({"app": this.appCode}).then(response => {

                this.queryFormData = response.data.data;


                // 系统参数
                if (this.queryFormData.param) {
                    for (let indexa = 0; indexa < this.queryFormData.param.length; indexa++) {
                        var paramTemp = this.queryFormData.param[indexa];
                        this.sysParamForm[paramTemp.pkey] = paramTemp.pvalue;
                    }
                }

              if(this.queryFormData.dics){

                // for (let kid in  this.queryFormData.dics) {
                //   let valuesm = this.queryFormData.dics[kid];
                //   this.tableDicMap[kid] = {};
                //   for (let ind = 0; ind < valuesm.length; ind++) {
                //     this.tableDicMap[kid][ valuesm[ind].value] = valuesm[ind].label;
                //   }
                // }

              }


                let mapCols = {};
                if (this.queryFormData.form) {
                   let  optionForm = eval("(" + this.queryFormData.form.modelJson + ")") || {};
                    optionForm.column.forEach((column) => {
                        mapCols[column.prop] = column;
                    });
                    if (optionForm.group) {
                        optionForm.group.forEach((groupItem) => {
                            if (groupItem.column) {
                                groupItem.column.forEach((column22) => {
                                    mapCols[column22.prop] = column22;
                                });
                            }
                        });
                    }
                }

                if (this.queryFormData.models) {
                    let selectcolumns = [];
                    let selectcolumnsGroup = [];

                    for (let indexf = 0; indexf < this.queryFormData.models.length; indexf++) {
                        let fied = this.queryFormData.models[indexf];
                        if (!!fied.isQuery) {
                            let selectcolumn = {
                                "type": fied.columnShowType || "input",
                                "label": fied.label,
                                "labelWidth":120,
                                "prop": fied.prop,
                                'search': !!fied.queryType && fied.queryType != "range",
                                "span": 12
                            }

                            if("id" ==  selectcolumn.prop){
                                selectcolumn.hide = true;
                            }
                            switch (selectcolumn.type) {
                                case "input":
                                    break;
                                case "number":

                                    break;
                                case "select":
                                    //selectcolumn.dicData = this.$dictObject[fied.dicValue];

                                  selectcolumn.dicData = fied.dicValue?this.queryFormData.dics[fied.dicValue]:this.queryFormData.dics[fied.prop];
                                    break;
                                case "radio":
                                  selectcolumn.dicData = fied.dicValue?this.queryFormData.dics[fied.dicValue]:this.queryFormData.dics[fied.prop];
                                    break;
                                case "checkbox":
                                  selectcolumn.dicData = fied.dicValue?this.queryFormData.dics[fied.dicValue]:this.queryFormData.dics[fied.prop];
                                    break;
                                case "switch":
                                    selectcolumn.dicData = [{"label": "否", "value": 0}, {"label": "是", "value": 1}];
                                    break;
                                case "date":
                                    selectcolumn.format = 'YYYY年MM月DD日';
                                    break;
                                case "datetime":
                                    selectcolumn.format = 'YYYY年MM月DD日 hh:mm';
                                    break;
                                case "year":
                                    selectcolumn.format = 'YYYY年';
                                    break;
                                case "week":
                                    selectcolumn.dateformat="week";
                                    //selectcolumn.type=  "input",
                                    break;
                                case "month":
                                    selectcolumn.format = 'YYYY年MM月';
                                    break;
                                case "time":
                                    selectcolumn.format = 'hh:mm';
                                    break;
                                case "cascader":
                                    break;
                                case "upload":
                                    selectcolumn.type = "upload";
                                    selectcolumn.listType = "picture-img";
                                    selectcolumn.addDisplay = false;
                                    selectcolumn.editDisplay = false;
                                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                                    break;
                                case "ueditor":
                                    selectcolumn.type = "ueditor";
                                    selectcolumn.overHidden = true;
                                    selectcolumn.component = "avueUeditor";
                                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";

                                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                                    selectcolumn.propsHttp = {
                                        // 上传完成返回的json的root
                                        "res": "data.data",
                                        // 上传完成返回的图片路径
                                        "url": "url",
                                        // 上传文件名，默认file
                                        "fileName": "file",
                                    };
                                    selectcolumn.search = false;
                                    selectcolumn.span = 24
                                    break;
                            }

                            let formColumn  = mapCols[fied.prop];
                            if(formColumn){
                                if(formColumn.dicData && !selectcolumn.dicData ) {
                                    selectcolumn.dicData = formColumn.dicData;
                                }
                            }
                            if(selectcolumn.dicData) {
                              this.tableDicMap[fied.prop] = {};
                              for (let ind = 0; ind < selectcolumn.dicData.length; ind++) {
                                this.tableDicMap[fied.prop][selectcolumn.dicData[ind].value] = selectcolumn.dicData[ind].label;
                              }
                            }



                            this.addRangSearch(selectcolumns,fied,selectcolumn);
                        }
                        if (!!fied.isGroup) {
                          let gcolumn = {"label": fied.label, "value": fied.prop}
                          gcolumn.txDics = [];
                          this.groupDics.push(gcolumn);

                          let groupTypeTemps = fied.groupType.split(",");
                          let groupJson = eval('(' + fied.groupJson + ')') || {};
                          for (let indexG = 0; indexG < groupTypeTemps.length; indexG++) {
                            let groupTypes = "";
                            switch (groupTypeTemps[indexG]) {
                              case "avg" :
                                groupTypes = "平均值";
                                break;
                              case "max" :
                                groupTypes = "最大值";
                                break;
                              case "min" :
                                groupTypes = "最小值";
                                break;
                              case "sum" :
                                groupTypes = "求和";
                                break;
                              case "count" :
                                groupTypes = "个数";
                                break;
                              case "other" :
                                groupTypes = "其他";
                                break;
                            }
                            let txcolumn = {
                              "label": fied.label + groupTypes,
                              "value": groupTypeTemps[indexG] + "_" + fied.prop
                            }
                            let asTitle = groupJson[groupTypes];
                            txcolumn.label = asTitle || (fied.label + groupTypes);
                            txcolumn.label = asTitle || (groupTypes);
                            this.groupTitleMap[txcolumn.value] = txcolumn.label;
                            gcolumn.txDics.push(txcolumn);

                            this.groupDicMap[gcolumn.value]=gcolumn;
                            let selectcolumn = {
                              "type": "input",
                              "label": txcolumn.label,
                              "prop": groupTypeTemps[indexG] + "_" + fied.prop,
                              'mgroup': true,
                              hide: true,
                              display: false,
                              'search': false,
                              "span": 12
                            }
                            selectcolumnsGroup.push(selectcolumn);
                          }
                        }


                    }

                    // 将统计字段放在最后
                    if(selectcolumnsGroup.length>0){
                        selectcolumns = selectcolumns.concat(selectcolumnsGroup);

                    }

                    this.option.column = selectcolumns;


                }
                 convertVantMobile( this.option,false);
                this.getPage();
            });

        },

        addRangSearch(selectcolumns,fied,selectcolumn) {
          if (fied.queryType != "range") {
            return
          }
          let selectcolumnStar = {
            "type": selectcolumn.type,
            "label": "开始" + selectcolumn.label,
            "prop": selectcolumn.prop + "Star",
            'search': true,
            "labelWidth": 120,
            "hide": true,
            "span": 12
          }
          if (selectcolumn.dicData) {
            selectcolumnStar.dicData = selectcolumn.dicData;
          }
          if (selectcolumnStar.dicCode) {
            selectcolumnStar.dicCode = selectcolumn.dicCode;
          }
          if (selectcolumnStar.format) {
            selectcolumnStar.format = selectcolumn.format;
          }
          selectcolumns.push(selectcolumnStar);

          let selectcolumnEnd = {
            "type": selectcolumn.type,
            "label": "结束" + selectcolumn.label,
            "prop": selectcolumn.prop + "End",
            'search': true,
            "labelWidth": 120,
            "hide": true,
            "span": 12
          }
          if (selectcolumnEnd.dicData) {
            selectcolumnEnd.dicData = selectcolumn.dicData;
          }
          if (selectcolumnEnd.dicCode) {
            selectcolumnEnd.dicCode = selectcolumn.dicCode;
          }
          if (selectcolumnEnd.format) {
            selectcolumnEnd.format = selectcolumn.format;
          }
          selectcolumns.push(selectcolumnEnd);
          this.rangList.push(selectcolumn.prop + "Star");
          this.rangList.push(selectcolumn.prop + "End");


        },
      getPage() {
        this.tableDataList = [];
        for (let index = 0; index < this.groupDics.length; index++) {
          let groupDic = this.groupDics[index];
          this.getPageOne(groupDic.value, groupDic.txDics.map(obj => obj.value).join(","),index);
        }
      },

        getPageOne(group,txs,index) {

          this.loading = true;
          let paramsData = this.buildParam(group, txs);
          return request({
            url: website.baseUrl + '/api/' + this.pageConfig.url + '/list',
            method: 'post',
            data: paramsData,
            params: {"app": this.appCode}
          }).then(response => {
            let dataObj = {};
            dataObj.index = index;
            let dic = this.groupDicMap[group];
            dataObj.clomns = [];
            //dataObj.clomns.push({k: dic.label, v: dic.value})
            dataObj.clomns.push({k:"选项", v: dic.value})
            dataObj.title = dic.label + "统计";

            for (let index = 0; index < dic.txDics.length; index++) {
              dataObj.clomns.push({k: dic.txDics[index].label, v: dic.txDics[index].value})
            }
            dataObj.data = response.data.data.data;
            let unNumDic = [];
            for (let vt in this.tableDicMap[group]) {
              unNumDic.push(vt);
            }
            for (let index = 0; index < dataObj.data.length; index++) {
              let d = dataObj.data[index];
              if(unNumDic.indexOf(d[group]) >=0) {
                unNumDic = unNumDic.filter(item => item !== d[group]);
              } else if (unNumDic.indexOf(d[group]) >= 0) {
                 // 多余的，多选
              }
              if (this.queryFormData.dics && this.tableDicMap[group]) {
                d[group] = this.tableDicMap[group][d[group]];
              }
            }
            for (let index = 0; index < unNumDic.length; index++) {
              let unNumObj = {};
              for (let indexCol = 0; indexCol < dataObj.clomns.length; indexCol++) {
                let vtemp = dataObj.clomns[indexCol].v;
                if (vtemp == group) {
                  unNumObj[vtemp] = this.tableDicMap[vtemp][unNumDic[index]];
                } else {
                  unNumObj[vtemp] = "0";
                }
              }
              dataObj.data.push(unNumObj);
            }
            //this.tableDataList.push(dataObj);
            this.tableDataList.splice(index, 0, dataObj);
            this.loading = false;
          })
              .catch(() => {
                this.loading = false;
              });
        },



        buildParam(group,txs) {
          let entity = Object.assign(
              {},
              {},
              this.form
          );
          let obj = {};
          obj.entity = removeEmptyFields(entity);
          obj.entity.group = true;
          obj.entity.groupStr = group;
          obj.entity.txsStr = txs;
          return obj;
        },
    }
  };
</script>
<style  >
 .my-group-data .avue-crud__body{
   display: none;
 }
</style>
